package com.ustc.hewei.rpc.client.discovery.impl;

import com.alibaba.fastjson2.JSON;
import com.ustc.hewei.rpc.client.discovery.ServiceDiscovery;
import com.ustc.hewei.rpc.common.protocol.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @description: 服务端在redis注册中心的发现
* @author hewei
* @date 2022/7/27 20:59
* @version 1.0
*/

@Slf4j
public class RedisDiscovery implements ServiceDiscovery {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Service> getServices(String serviceName) {
        String key = "rpc/" + serviceName + "/service";
        Set<String> members = stringRedisTemplate.opsForSet().members(key);
        //如果redis中没有对应的服务，返回空列表
        if (members == null) {
            log.error("服务 {} 未注册", serviceName);
            return Collections.emptyList();
        }
        return members.stream()
                .map(s -> JSON.parseObject(s, Service.class))
                .collect(Collectors.toList());
    }
}
